<script setup lang="ts">
import { baseURL } from '@/utils/http'
import { ref, onMounted } from 'vue'
import { useMemberStore } from '@/stores'
import type { userItem } from '@/types/member'
import { postUserRealNameAPI } from '@/api/account'
import { getCodeRealNameAPI } from '@/api/global'

const memberStore = useMemberStore()

// 获取企业信息
const form = ref<userItem>({})

const callAliyunMarketApi = async (imgurl: string, idCardSide: string) => {
  const appCode = '5ec86acbba7e41baa1228fb01b422caa' // 替换为你的AppCode
  let string = `image=${imgurl}&idCardSide=${idCardSide}`
  await uni.request({
    url: 'https://ocridcard.market.alicloudapi.com/idimages',
    method: 'POST', // 根据API要求使用POST或其他方法
    data: string,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'Authorization': 'AppCode ' + appCode, // 设置认证头部
    },
    success: (res:any) => {
      if (res.data.code == '1' && idCardSide == 'front') {
        console.log(res)
        form.value!.frontCardImage = imgurl
        form.value.name = res.data.result.name
        form.value.idCard = res.data.result.code
        uni.showToast({ icon: 'success', title: '上传成功' })
      }
      if (res.data.code == '1' && idCardSide == 'back') {
        form.value!.backCardImage = imgurl
        uni.showToast({ icon: 'success', title: '上传成功' })
      }
      if (res.data.code == '2') {
        form.value!.backCardImage = imgurl
        uni.showToast({ icon: 'success', title: '上传成功' })
      }
      if (res.data.code == '-1') {
        uni.showToast({ icon: 'error', title: '图像为空' })
        return false
      }
      if (res.data.code == '-2') {
        uni.showToast({ icon: 'error', title: '图像格式错误' })
        return false
      }
      if (res.data.code == '-3') {
        uni.showToast({ icon: 'error', title: '图像无法加载' })
        return false
      }
      if (res.data.code == '-4') {
        uni.showToast({ icon: 'error', title: '图像识别失败' })
        return false
      }
      if (res.data.code == '-5') {
        uni.showToast({ icon: 'error', title: '身份证模糊,反光,太暗' })
        return false
      }
      if (res.data.code == '-6') {
        uni.showToast({ icon: 'error', title: '身份证正反面错误' })
        return false
      }
      if (res.data.code == '-7') {
        uni.showToast({ icon: 'error', title: '身份证图片不完整或其他证件' })
        return false
      }
      if (res.data.code == '-9') {
        uni.showToast({ icon: 'error', title: '没有信息' })
        return false
      }
    },
    fail: (err:any) => {
      return err.data.code
    },
  })
}

onMounted(() => {
  form.value = memberStore.profile
})

// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  name: {
    rules: [{ required: true, errorMessage: '请输入姓名' }],
  },
  nickname: {
    rules: [{ required: true, errorMessage: '请输入昵称' }],
  },
  contactsPhone: {
    rules: [
      { required: true, errorMessage: '请输入手机号码' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
    ],
  },
  mobileCode: {
    rules: [{ required: true, errorMessage: '请输入手机验证码' }],
  },
  frontCardImage: {
    rules: [{ required: true, errorMessage: '请上传身份证正面' }],
  },
  backCardImage: {
    rules: [{ required: true, errorMessage: '请上传身份证背面' }],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请输入身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        errorMessage: '身份证号格式不正确',
      },
    ],
  },
}

// 获取表单组件实例，用于调用表单方法
const formRef = ref<UniHelper.UniFormsInstance>()

const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value?.validate?.()
    const res = await postUserRealNameAPI(form.value)
    uni.showToast({ icon: 'success', title: res.data as string })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/attes/attes' })
    }, 1000)
  } catch (error) {
    uni.showToast({ icon: 'error', title: '请填写完整信息' })
  }
}

// 修改图片
const onAvatarChange = (type: string) => {
  // 调用拍照/选择图片
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 文件上传
      uni.uploadFile({
        url: '/admin/sys-file/upload',
        name: 'file', // 后端数据字段名
        filePath: tempFilePath, // 新头像
        success: (res) => {
          // 判断状态码是否上传成功
          if (res.statusCode === 200) {
            // 提取图片地址
            let { url } = JSON.parse(res.data).data
            url = 'https://qianxiangmall.com/api' + url
            // 当前页面更新图片信息
            if (type == 'frontCard') {
              callAliyunMarketApi(url, 'front')
            }
            if (type == 'backCard') {
              callAliyunMarketApi(url, 'back')
            }
          } else {
            uni.showToast({ icon: 'error', title: '出现错误' })
          }
        },
      })
    },
  })
}

// 删除图片
const clearImg = (type: string) => {
  if (type == 'frontCard') {
    form.value!.frontCardImage = ''
  }
  if (type == 'backCard') {
    form.value!.backCardImage = ''
  }
  uni.showToast({ icon: 'success', title: '删除成功' })
}

// 获取验证码
const count = ref(60)
const counting = ref(false)
const getCode = ref('')

const getCodeRegist = async () => {
  if (form.value.contactsPhone) {
    const res = await getCodeRealNameAPI(form.value.contactsPhone)
    if (res.code == '0') {
      getCode.value = res.msg
      uni.showToast({
        icon: 'none',
        title: '验证码发送成功，请查看手机短信！',
      })
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      })
    }
    counting.value = true
    const timer = setInterval(() => {
      count.value--
      if (count.value <= 0) {
        clearInterval(timer)
        counting.value = false
        count.value = 60 // 重置倒计时时长
      }
    }, 1000)
  } else {
    uni.showToast({
      icon: 'none',
      title: '请输入手机号',
    })
  }
}
</script>
<template>
  <!-- 表单 -->
  <uni-forms :rules="rules" :model="form" ref="formRef" class="form">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms-item class="form-item" name="name">
        <text class="label">姓名</text>
        <input class="input" type="text" placeholder="请填写" v-model="form.name" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="nickname">
        <text class="label">昵称</text>
        <input class="input" type="text" placeholder="请填写" v-model="form.nickname" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="idCard">
        <text class="label">身份证号</text>
        <input class="input" maxlength="18" placeholder="请填写" v-model="form.idCard" />
      </uni-forms-item>
      <uni-forms-item class="form-item image_upload" name="frontCardImage">
        <text class="label">身份证正面</text>
        <view v-if="!form.frontCardImage" class="upload" @tap="onAvatarChange('frontCard')">
          <uni-icons type="plusempty" color="#ddd" size="40" />
        </view>
        <view v-else class="company_img">
          <image :src="form.frontCardImage" mode="aspectFill" />
          <view class="close" @tap="clearImg('frontCard')">X</view>
        </view>
      </uni-forms-item>
      <uni-forms-item class="form-item image_upload" name="backCardImage">
        <text class="label">身份证背面</text>
        <view v-if="!form.backCardImage" class="upload" @tap="onAvatarChange('backCard')">
          <uni-icons type="plusempty" color="#ddd" size="40" />
        </view>
        <view v-else class="company_img">
          <image :src="form.backCardImage" mode="aspectFill" />
          <view class="close" @tap="clearImg('backCard')">X</view>
        </view>
      </uni-forms-item>
      <uni-forms-item name="contactsPhone" class="form-item">
        <text class="label">电话号码</text>
        <input
          class="input phone_input"
          type="text"
          placeholder="请填写"
          v-model="form.contactsPhone"
        />
        <button class="code send" :disabled="counting" @tap="getCodeRegist">
          {{ counting ? `${count}秒后重新获取` : '获取验证码' }}
        </button>
      </uni-forms-item>
      <uni-forms-item name="mobileCode" class="form-item">
        <text class="label">验证码</text>
        <input class="input" type="text" placeholder="请填写" v-model="form.mobileCode" />
      </uni-forms-item>
    </view>
    <!-- 提交按钮 -->
    <button class="form-button" @tap="onSubmit">修改信息</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
.company_img {
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  background-color: rgba($color: #000000, $alpha: 0.5);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
